package com.szly.phm.common.utils;


import com.szly.phm.common.entity.result.CodeStatusEnum;
import jodd.http.HttpBase;
import jodd.http.HttpRequest;
import jodd.net.HttpStatus;

import java.util.HashMap;
import java.util.Map;

public class HttpRemoteUtils {

    public static Map<String,String> post(String postURL, Map<String, String> queryMap) {
        var map = new HashMap<String,String>();
        var request = HttpRequest.post(postURL)
                .query(queryMap)
                .charset(HttpBase.Defaults.bodyEncoding)
                //指定返回的格式及编码
                .accept("application/json;charset=UTF-8");
        final var response = request.send();
        if (response.statusCode() != HttpStatus.ok().status()) {
            map.put("code",String.valueOf(response.statusCode()));
            map.put("message"," 外部接口【" + postURL + "】调用失败了！");
            return map;
        }
        final var s = response.bodyText();
        map.put("code", CodeStatusEnum.SUCCESS.getCode());
        map.put("message",CodeStatusEnum.SUCCESS.getMessage());
        map.put("data",s);
        return map;
    }

    public static Map<String,String> postForm(String postURL, Map<String, Object> queryMap) {
        var map = new HashMap<String,String>();
        var request = HttpRequest.post(postURL).form(queryMap).charset("UTF-8");
        request.charset("UTF-8");
        final var response = request.send();
        if (response.statusCode() != HttpStatus.ok().status()) {
            map.put("code",String.valueOf(response.statusCode()));
            map.put("message"," 外部接口【" + postURL + "】调用失败了！");
            return map;
        }
        final var s = response.bodyText();
        map.put("code", CodeStatusEnum.SUCCESS.getCode());
        map.put("message",CodeStatusEnum.SUCCESS.getMessage());
        map.put("data",s);
        return map;
    }

    public static Map<String,String> get(String getURL) {
        var map = new HashMap<String,String>();
        var request = HttpRequest.get(getURL).charset("UTF-8");
        final var response = request.send();
        if (response.statusCode() != HttpStatus.ok().status()) {
            map.put("code",String.valueOf(response.statusCode()));
            map.put("message"," 外部接口【" + getURL + "】调用失败了！");
            return map;
        }
        final var s = response.bodyText();
        map.put("code", CodeStatusEnum.SUCCESS.getCode());
        map.put("message",CodeStatusEnum.SUCCESS.getMessage());
        map.put("data",s);
        return map;
    }

    public static String getHttp(String getURL) {
        var request = HttpRequest.get(getURL).charset("UTF-8");
        final var response = request.send();
        if (response.statusCode() != HttpStatus.ok().status()) {
            return "999";
        }
        final var s = response.bodyText();
        return s;
    }
}